package com.example.gomi.intelligentcitypipe.DAO;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * Created by GoMi on 16/6/30.
 */
public class DataBaseHelper_ormlite extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "ormlite.db";
    private static final int DATABASE_VERSION = 1;

    private Dao<PipeInfo,Integer> mPipeInfoDao;

    public DataBaseHelper_ormlite(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            Log.i(DataBaseHelper_ormlite.class.getName(), "onCreate");
            TableUtils.createTable(connectionSource, PipeInfo.class);
        } catch (SQLException e) {
            Log.e(DataBaseHelper_ormlite.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            Log.i(DataBaseHelper_ormlite.class.getName(), "onUpgrade");
            TableUtils.dropTable(connectionSource, PipeInfo.class, true);
            // after we drop the old databases, we create the new ones
            // 会终止旧的数据库，会创建一个新的数据库
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            Log.e(DataBaseHelper_ormlite.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }

    public Dao<PipeInfo,Integer> getPipeInfoDao() throws SQLException {
        if (mPipeInfoDao ==null){
            mPipeInfoDao = getDao(PipeInfo.class);
        }
        return mPipeInfoDao;
    }
    @Override
    public void close() {//关闭Dao
        super.close();
        mPipeInfoDao = null;
    }
}
